# 由于代码较长，我将分几个部分修改

# 首先修改模板部分
<template>
  <div class="activity-management management-page">
    <!-- 搜索和筛选区域 -->
    <el-card class="filter-card" shadow="never">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="活动名称">
          <el-input
            v-model="searchForm.name"
            placeholder="请输入活动名称"
            clearable
            @keyup.enter="handleSearch"
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="活动类型">
          <el-select 
            v-model="searchForm.type" 
            placeholder="请选择活动类型" 
            clearable 
            style="width: 160px"
          >
            <el-option 
              v-for="(label, type) in activityTypeMap" 
              :key="type"
              :label="label" 
              :value="type" 
            />
          </el-select>
        </el-form-item>
        <el-form-item label="年份筛选">
          <el-date-picker
            v-model="searchForm.year"
            type="year"
            placeholder="选择年份"
            format="YYYY"
            value-format="YYYY"
            style="width: 120px"
          />
        </el-form-item>
        <el-form-item class="search-buttons">
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>搜索
          </el-button>
          <el-button @click="resetSearch">
            <el-icon><Refresh /></el-icon>重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 活动列表 -->
    <el-card class="list-card" shadow="never">
      <template #header>
        <div class="card-header">
          <div class="header-left">
            <span class="header-title">活动列表</span>
            <el-tag type="info" class="header-count" size="small">
              共 {{ total }} 条
            </el-tag>
          </div>
          <div class="header-operations">
            <el-button type="primary" @click="showAddDialog">
              <el-icon><Plus /></el-icon>添加活动
            </el-button>
            <el-button 
              type="danger" 
              :disabled="!selectedActivities.length"
              @click="handleBatchDelete"
            >
              <el-icon><Delete /></el-icon>
              批量删除 {{ selectedActivities.length ? `(${selectedActivities.length})` : '' }}
            </el-button>
          </div>
        </div>
      </template>

      <el-table
        v-loading="loading"
        :data="activityList"
        @selection-change="handleSelectionChange"
        style="width: 100%"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column label="活动图片" width="120">
          <template #default="{ row }">
            <el-image
              :src="row.img"
              :preview-src-list="[row.img]"
              fit="cover"
              style="width: 80px; height: 80px; border-radius: 4px;"
              :initial-index="0"
            >
              <template #error>
                <div class="image-error">
                  <el-icon><Picture /></el-icon>
                </div>
              </template>
            </el-image>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="活动名称" min-width="150" show-overflow-tooltip>
          <template #default="{ row }">
            <el-button type="primary" link @click="handleViewDetail(row)">
              {{ row.name }}
            </el-button>
          </template>
        </el-table-column>
        <el-table-column prop="type" label="活动类型" width="150">
          <template #default="{ row }">
            <el-tag :type="getActivityTypeTagType(row.type as ActivityType)">
              {{ activityTypeMap[row.type as ActivityType] }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="time" label="活动时间" width="180" />
        <el-table-column prop="description" label="活动描述" min-width="200" show-overflow-tooltip />
        <el-table-column label="活动文件" min-width="120">
          <template #default="{ row }">
            <div v-if="row.url" class="file-info">
              <el-button type="primary" link @click="previewFile(row)">
                预览文件
              </el-button>
              <el-button type="primary" link :href="row.url" target="_blank">
                下载文件
              </el-button>
            </div>
            <span v-else class="no-file">暂无文件</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleEdit(row)">
              <el-icon><Edit /></el-icon>编辑
            </el-button>
            <el-button type="danger" link @click="handleDelete(row)">
              <el-icon><Delete /></el-icon>删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 活动表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '添加活动' : '编辑活动'"
      width="650px"
      @close="resetForm"
    >
      <el-form
        ref="activityFormRef"
        :model="activityForm"
        :rules="activityRules"
        label-width="100px"
        class="activity-form"
      >
        <el-form-item label="活动名称" prop="name">
          <el-input 
            v-model="activityForm.name"
            placeholder="请输入活动名称"
            maxlength="50"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="活动类型" prop="type">
          <el-select 
            v-model="activityForm.type"
            placeholder="请选择活动类型"
            style="width: 100%"
          >
          <el-option 
            v-for="(label, type) in Object.fromEntries(
              Object.entries(activityTypeMap).filter(([key]) => key !== ActivityType.ALL)
            )"
            :key="type"
            :label="label" 
            :value="type" 
          />
          </el-select>
        </el-form-item>

        <el-form-item label="活动时间" prop="time">
          <el-date-picker
            v-model="activityForm.time"
            type="datetime"
            placeholder="请选择活动时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            :shortcuts="[
              {
                text: '今天',
                value: new Date(),
              },
              {
                text: '明天',
                value: () => {
                  const date = new Date()
                  date.setTime(date.getTime() + 3600 * 1000 * 24)
                  return date
                },
              },
              {
                text: '一周后',
                value: () => {
                  const date = new Date()
                  date.setTime(date.getTime() + 3600 * 1000 * 24 * 7)
                  return date
                },
              }
            ]"
          />
        </el-form-item>

        <el-form-item label="活动描述" prop="description">
          <el-input
            v-model="activityForm.description"
            type="textarea"
            :rows="4"
            placeholder="请输入活动描述"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="活动图片" prop="image" class="upload-item">
          <el-upload
            class="activity-upload"
            :auto-upload="false"
            :show-file-list="true"
            :limit="1"
            accept="image/*"
            :on-change="handleImageChange"
            :on-remove="handleImageRemove"
          >
            <template #default>
              <div class="upload-trigger">
                <el-icon><Plus /></el-icon>
                <span>选择图片</span>
              </div>
            </template>
            <template #tip>
              <div class="el-upload__tip">
                只能上传 jpg/png 格式图片，且不超过 5MB
              </div>
            </template>
          </el-upload>
          <div v-if="previewImage" class="image-preview">
            <el-image :src="previewImage" fit="cover" />
          </div>
        </el-form-item>

        <el-form-item label="活动文件" prop="file" class="upload-item">
          <el-upload
            class="activity-upload"
            :auto-upload="false"
            :show-file-list="true"
            :limit="1"
            :on-change="handleFileChange"
            :on-remove="handleFileRemove"
          >
            <template #default>
              <div class="upload-trigger">
                <el-icon><Plus /></el-icon>
                <span>选择文件</span>
              </div>
            </template>
            <template #tip>
              <div class="el-upload__tip">
                支持各种格式文件，且不超过 50MB
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitting">
            {{ dialogType === 'add' ? '创建' : '更新' }}
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 活动详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="活动详情"
      width="600px"
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="活动名称" :span="2">
          {{ currentActivity?.name }}
        </el-descriptions-item>
        <el-descriptions-item label="活动类型">
          <el-tag :type="getActivityTypeTagType(currentActivity?.type)">
            {{ activityTypeMap[currentActivity?.type as ActivityType] }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="活动时间">
          {{ currentActivity?.time }}
        </el-descriptions-item>
        <el-descriptions-item label="活动描述" :span="2">
          {{ currentActivity?.description }}
        </el-descriptions-item>
        <el-descriptions-item label="活动图片" :span="2">
          <el-image
            v-if="currentActivity?.img"
            :src="currentActivity.img"
            fit="cover"
            style="width: 200px; height: 200px; border-radius: 4px;"
          />
        </el-descriptions-item>
        <el-descriptions-item label="活动文件" :span="2">
          <div v-if="currentActivity?.url" class="file-info">
            <el-link type="primary" :href="currentActivity.url" target="_blank">查看文件</el-link>
            <el-button type="danger" link @click="handleDeleteFile(currentActivity.id)">
              <el-icon><Delete /></el-icon>删除
            </el-button>
          </div>
          <span v-else>暂无文件</span>
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules, UploadFile } from 'element-plus'
import {
  Search,
  Refresh,
  Plus,
  Delete,
  Edit,
  Picture
} from '@element-plus/icons-vue'
import {
  getActivityList,
  addActivity,
  updateActivity,
  deleteActivity,
  batchDeleteActivities,
  uploadActivityImage,
  uploadActivityFile,
  deleteActivityFile,
  ActivityType,
  type Activity,
  type ActivityCreateRequest
} from '@/api/activity'
import { JsonData } from '@/api/meeting'

// 活动类型映射
const activityTypeMap: Record<ActivityType, string> = {
  [ActivityType.ALL]: '全部类型',
  [ActivityType.DIGITAL]: '数字成果展',
  [ActivityType.PRODUCT]: '新品发布',
  [ActivityType.SAFETY]: '安全特训营',
  [ActivityType.SCIENCE]: '科学创新',
  [ActivityType.ECOLOGY]: '生态发展'
}

// 状态
const loading = ref(false)
const submitting = ref(false)
const dialogVisible = ref(false)
const detailDialogVisible = ref(false)
const dialogType = ref<'add' | 'edit'>('add')
const activityList = ref<Activity[]>([])
const selectedActivities = ref<Activity[]>([])
const currentActivity = ref<Activity>()
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const previewImage = ref('')

// 表单相关
const activityFormRef = ref<FormInstance>()
const searchForm = reactive({
  name: '',
  type: ActivityType.ALL,
  year: ''
})

const activityForm = reactive({
  id: 0,
  pubId: 0,
  name: '',
  type: ActivityType.DIGITAL,
  description: '',
  time: '',
  img: '',  
  url: '',   
  image: null as File | null,
  file: null as File | null
})

// 表单校验规则
const activityRules: FormRules = {
  name: [
    { required: true, message: '请输入活动名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择活动类型', trigger: 'change' }
  ],
  description: [
    { required: true, message: '请输入活动描述', trigger: 'blur' },
    { max: 500, message: '描述不能超过500个字符', trigger: 'blur' }
  ],
  time: [
    { required: true, message: '请输入活动时间', trigger: 'blur' }
  ],
  image: [
    { required: true, message: '请上传活动图片', trigger: 'change' }
  ],
  file: [
    { required: true, message: '请上传活动文件', trigger: 'change' }
  ]
}

// 获取活动类型标签样式
const getActivityTypeTagType = (type?: ActivityType): '' | 'success' | 'warning' | 'danger' | 'info' => {
  const map: Record<ActivityType, '' | 'success' | 'warning' | 'danger' | 'info'> = {
    [ActivityType.ALL]: '',
    [ActivityType.DIGITAL]: 'success',
    [ActivityType.PRODUCT]: 'warning',
    [ActivityType.SAFETY]: 'danger',
    [ActivityType.SCIENCE]: 'info',
    [ActivityType.ECOLOGY]: 'success'
  }
  return type ? map[type] : ''
}

// 获取活动列表
const fetchActivityList = async () => {
  loading.value = true
  try {
    const response = await getActivityList({
      page: currentPage.value,
      size: pageSize.value,
      name: searchForm.name || undefined,
      type: searchForm.type === ActivityType.ALL ? undefined : searchForm.type,
      year: searchForm.year ? parseInt(searchForm.year) : undefined
    })
    // 明确类型转换以避免TS错误
    if (response.data && typeof response.data === 'object') {
      activityList.value = (response.data as any).current_data || []
      total.value = (response.data as any).total_record || 0
    }
  } catch (error) {
    console.error('获取活动列表失败:', error)
    ElMessage.error('获取活动列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索和重置
const handleSearch = () => {
  currentPage.value = 1
  fetchActivityList()
}

const resetSearch = () => {
  searchForm.name = ''
  searchForm.type = ActivityType.ALL
  searchForm.year = ''
  handleSearch()
}

// 分页处理
const handleSizeChange = (val: number) => {
  pageSize.value = val
  fetchActivityList()
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
  fetchActivityList()
}

// 文件上传处理
const handleImageChange = (file: UploadFile) => {
  const isImage = file.raw?.type.startsWith('image/')
  const isLt5M = file.size! / 1024 / 1024 < 5

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过 5MB!')
    return false
  }

  activityForm.image = file.raw!
  if (file.raw) {
    previewImage.value = URL.createObjectURL(file.raw)
  }
}

const handleImageRemove = () => {
  activityForm.image = null
  previewImage.value = ''
}

const handleFileChange = (file: UploadFile) => {
  const isLt50M = file.size! / 1024 / 1024 < 50

  if (!isLt50M) {
    ElMessage.error('文件大小不能超过 50MB!')
    return false
  }

  activityForm.file = file.raw!
}

const handleFileRemove = () => {
  activityForm.file = null
}

// 表单操作
const showAddDialog = () => {
  dialogType.value = 'add'
  resetForm()
  dialogVisible.value = true
}

const handleEdit = (row: Activity) => {
  dialogType.value = 'edit'
  Object.assign(activityForm, row)
  if (row.img) {
    previewImage.value = row.img
  }
  dialogVisible.value = true
}

const handleViewDetail = (row: Activity) => {
  currentActivity.value = row
  detailDialogVisible.value = true
}

const resetForm = () => {
  if (activityFormRef.value) {
    activityFormRef.value.resetFields()
  }
  Object.assign(activityForm, {
    id: 0,
    pubId: 0,
    name: '',
    type: ActivityType.DIGITAL,
    description: '',
    time: '',
    img: '',
    url: '',
    image: null,
    file: null
  })
  previewImage.value = ''
}

// 提交表单
const handleSubmit = async () => {
  if (!activityFormRef.value) return
  
  try {
    await activityFormRef.value.validate()
    submitting.value = true

    // 创建要提交的数据对象
    const activityData: ActivityCreateRequest = {
      name: activityForm.name,
      type: activityForm.type,
      description: activityForm.description,
      time: activityForm.time,
      img: '',
      url: activityForm.url
    }

    // 处理文件上传
    try {
      // 上传图片（必须项）
      if (activityForm.image) {
        const imageRes = await uploadActivityImage(activityForm.image)
        // 检查响应数据
        if (!imageRes.data) {
          throw new Error('图片上传失败，未获取到URL')
        }
        activityData.img = imageRes.data as string
      } else if (dialogType.value === 'edit' && activityForm.img) {
        // 编辑模式且有原图片URL
        activityData.img = activityForm.img
      } else {
        throw new Error('请上传活动图片')
      }

      // 上传文件（可选项）
      if (activityForm.file) {
        const fileRes = await uploadActivityFile(activityForm.file)
        // 检查响应数据
        if (!fileRes.data) {
          throw new Error('文件上传失败，未获取到URL')
        }
        activityData.url = fileRes.data as string
      } else if (dialogType.value === 'edit' && activityForm.url) {
        // 编辑模式且有原文件URL
        activityData.url = activityForm.url
      }

      // 提交活动数据
      if (dialogType.value === 'add') {
        await addActivity(activityData)
        ElMessage.success('添加活动成功')
      } else {
        await updateActivity(activityForm.id, activityData)
        ElMessage.success('更新活动成功')
      }

      dialogVisible.value = false
      fetchActivityList()
    } catch (uploadError: any) {
      console.error('文件处理失败:', uploadError)
      ElMessage.error(uploadError.message || '文件处理失败')
      throw uploadError // 继续抛出错误以终止处理
    }
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error(error instanceof Error ? error.message : '提交失败')
  } finally {
    submitting.value = false
  }
}

// 删除操作
const handleDelete = (row: Activity) => {
  ElMessageBox.confirm(
    '确认删除该活动？此操作不可恢复',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await deleteActivity(row.id)
      ElMessage.success('删除成功')
      fetchActivityList()
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  })
}

const handleSelectionChange = (selection: Activity[]) => {
  selectedActivities.value = selection
}

const handleBatchDelete = () => {
  if (!selectedActivities.value.length) {
    ElMessage.warning('请选择要删除的活动')
    return
  }

  ElMessageBox.confirm(
    `确认删除选中的 ${selectedActivities.value.length} 个活动？此操作不可恢复`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await batchDeleteActivities(selectedActivities.value.map(item => item.id))
      ElMessage.success('批量删除成功')
      fetchActivityList()
    } catch (error) {
      console.error('批量删除失败:', error)
      ElMessage.error('批量删除失败')
    }
  })
}

// 删除文件
const handleDeleteFile = async (activityId: number) => {
  try {
    await deleteActivityFile(activityId)
    ElMessage.success('文件删除成功')
    fetchActivityList()
  } catch (error) {
    console.error('文件删除失败:', error)
    ElMessage.error('文件删除失败')
  }
}

const previewFile = (row: Activity) => {
  // 检查文件类型
  const fileUrl = row.url;
  if (!fileUrl) return;
  
  // 如果是PDF，在新窗口打开
  if (fileUrl.toLowerCase().endsWith('.pdf')) {
    window.open(fileUrl, '_blank');
  } else {
    // 其他类型文件直接下载
    const link = document.createElement('a');
    link.href = fileUrl;
    link.download = row.name || 'download';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  }
}

onMounted(() => {
  fetchActivityList()
})
</script>

<style lang="scss" scoped>
@import '@/styles/common.scss';

.activity-management {
  .image-error {
    width: 80px;
    height: 80px;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #f5f7fa;
    border-radius: 4px;
    color: #909399;
  }

  .file-info {
    display: flex;
    align-items: center;
    gap: 8px;

    .file-name {
      color: #409eff;
      cursor: pointer;
      max-width: 200px;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;

      &:hover {
        color: #79bbff;
      }
    }

    .file-size {
      color: #909399;
      font-size: 12px;
    }
  }

  .no-file {
    color: #909399;
    font-size: 12px;
  }

  .activity-upload {
    @extend .upload-container;
  }

  .image-preview {
    margin-top: 10px;
    width: 120px;
    height: 120px;
    border-radius: 4px;
    overflow: hidden;

    .el-image {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
  }
}
</style>